#include "StdAfx.h"
#include "CommDevice.h"


CCommDevice::CCommDevice(void)
	: m_hCommPort(NULL)
	, m_hCommDevice(NULL)
{
	this->OnCommandError = [](CCommDevice*, BYTE){};
	this->OnCoinIn = [](CCommDevice*, BYTE){};
	this->OnCoinOut = [](CCommDevice*, BYTE, BYTE){};
	this->OnKeyboardEvent = [](CCommDevice*, BYTE, BYTE){};
}


CCommDevice::~CCommDevice(void)
{
	this->Close();
}


BOOL CCommDevice::Open(LPCTSTR szComm, BYTE cAddr)
{
	m_hCommPort = ::OpenCommPort(szComm);
	if (m_hCommPort)
	{
		m_hCommDevice = ::AddCommDevice(m_hCommPort, cAddr, (COMMDEVICECALLBACK)_RecvCommand, this);
		if (m_hCommDevice)
			return TRUE;

		::CloseCommPort(m_hCommPort);
		m_hCommPort = NULL;
	}
	return FALSE;
}
void CCommDevice::Close(void)
{
	if (m_hCommDevice)
	{
		::RemoveCommDevice(m_hCommPort, m_hCommDevice);
		::CloseCommPort(m_hCommPort);
		m_hCommPort = NULL;
		m_hCommDevice = NULL;
	}
}

/* static */
void CCommDevice::_RecvCommand(HCOMMDEVICE, CommData* pCmd, CCommDevice* pDevice)
{
	switch (pCmd->head)
	{
	case CommData::H_ERROR:
		pDevice->OnCommandError(pDevice, pCmd->param[0]);
		break;
	case CommData::H_COIN_IN:
		pDevice->OnCoinIn(pDevice, pCmd->param[0]);
		break;
	case CommData::H_COIN_OUT:
		pDevice->OnCoinOut(pDevice, pCmd->param[0], pCmd->param[1]);
		break;
	case CommData::H_KEY_EVENT:
		pDevice->OnKeyboardEvent(pDevice, pCmd->param[0], pCmd->param[1]);
		break;
	}
}

